package com.ez.supervise.action.sys;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.ez.supervise.action.base.BaseJsonAction;
import com.ez.supervise.action.biz.OrgDemocracyAction;
import com.ez.supervise.model.dto.LoginUser;
import com.ez.supervise.model.dto.Menu;
import com.ez.supervise.model.sys.Org;
import com.ez.supervise.model.sys.Permission;
import com.ez.supervise.model.sys.User;
import com.ez.supervise.service.OrgService;
import com.ez.supervise.service.UserService;


public class LoginAction extends BaseJsonAction {

    private static final long serialVersionUID = -5518852930743786005L;

    public static final String SUCCESS_MANAGER = "success_manager";

    private UserService userService;
    
    private OrgService orgService;

    public void setOrgService(OrgService orgService) {
        this.orgService = orgService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    private User user;

    private boolean success;

    private Long id;

    private String tip;

    private String userName;

    private String password;

    private List<Permission> permissions;

    public String login() {
	if(StringUtils.isBlank(userName) || StringUtils.isBlank(password)){
	    return INPUT;
	}
	User user = userService.login(userName, password);
//	test set default user
//	user = new User(); user.setId(1L);
	if (user != null) {
	    LoginUser  loginUser =  new LoginUser(user);
	    
	    if(user.getOrgId() != null) {
		Org org = (Org)orgService.get(user.getOrgId());
		if(org != null){
		    loginUser.setOrgName(org.getName());
		}
		permissions = permissionService.findPermission(user.getId());
		Menu menu = new Menu(permissions);
		String script = menu.toScript();
		setScript(script);
	    }
	    registerLoginUser(loginUser);
	    return SUCCESS;
	} else {
	    clearLoginUser();
	    return INPUT;
	}
    }
    
    public String checkUser(){
	if(StringUtils.isBlank(userName) || StringUtils.isBlank(password)){
	    return INPUT;
	}
	User user = userService.login(userName, password);
	if(user!=null){
	    outJsonString(RESULT_SUCCESS);
	} else {
	    outJsonString(RESULT_FAIL);
	}
	return SUCCESS;
    }
    public String logout() {
	clearLoginUser();
	OrgDemocracyAction.clearDemocracyScoreList();
	success = true;
	return SUCCESS;
    }

    public void setUserName(String userName) {
	this.userName = userName;
    }

    public String getUserName() {
	return userName;
    }

    public void setPassword(String password) {
	this.password = password;
    }

    public String getPassword() {
	return password;
    }

}
